
package biblio.service.category;


import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.apache.log4j.Logger;


/**
 * Validates setting name of category.
 * @author mephisto
 */
@ManagedBean
@RequestScoped
public class CategoryValidator implements Validator
{
    public void validate(FacesContext context, UIComponent component, Object value)
            throws ValidatorException
    {
        if (value != null)
        {
            String val = value.toString().trim();
            log.info("Value to validate: " + val);
            if (autocompleteCategory.getAutocompleteList().indexOf(val) < 0)
            {
                FacesMessage message = new FacesMessage(
                           "Error by adding a new category", "Parent category does not exist!");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
    }

    public void setAutocompleteCategory(AutocompleteCategory autocompleteCategory)
    {
        this.autocompleteCategory = autocompleteCategory;
    }

    private static Logger log = Logger.getLogger(CategoryValidator.class);
    @ManagedProperty(value="#{autocompleteCategory}")
    private AutocompleteCategory autocompleteCategory;
}
